extends Node2D

var start_point = Vector2.ZERO
var end_point = Vector2.ZERO
var is_critical = false
var lifetime = 0.5  # 闪电效果持续时间（秒）

var time_alive = 0.0
var lightning_points = []  # 用于存储闪电的锯齿形路径点
var lightning_width = 3.0  # 闪电宽度
var lightning_color = Color(0.5, 0.7, 1.0, 0.8)  # 闪电颜色

func _ready():
	# 生成闪电路径
	generate_lightning_path()
	
	# 如果是暴击，调整颜色和宽度
	if is_critical:
		lightning_color = Color(1.0, 0.7, 0.3, 0.9)  # 暴击时颜色更偏黄色
		lightning_width = 5.0  # 暴击时宽度更大

func _process(delta):
	# 更新生命周期
	time_alive += delta
	
	# 更新透明度（逐渐消失）
	var alpha = 1.0 - (time_alive / lifetime)
	lightning_color.a = alpha * 0.8
	
	# 重绘闪电
	queue_redraw()
	
	# 到达最大存活时间后消失
	if time_alive >= lifetime:
		queue_free()

func _draw():
	# 绘制闪电
	if lightning_points.size() >= 2:
		for i in range(lightning_points.size() - 1):
			draw_line(lightning_points[i], lightning_points[i + 1], lightning_color, lightning_width)
	
	# 绘制闪电光晕（可选）
	if is_critical:
		for i in range(lightning_points.size() - 1):
			var glow_color = lightning_color
			glow_color.a = 0.3
			draw_line(lightning_points[i], lightning_points[i + 1], glow_color, lightning_width * 2.5)

func generate_lightning_path():
	# 清空现有路径
	lightning_points.clear()
	
	# 添加起点
	lightning_points.append(to_local(start_point))
	
	# 计算总距离和方向
	var total_distance = start_point.distance_to(end_point)
	var main_direction = (end_point - start_point).normalized()
	
	# 生成锯齿形路径
	var current_point = start_point
	var segment_length = total_distance / 8.0  # 分成8段
	
	for i in range(7):  # 生成中间的7个点
		var segment_direction = main_direction
		
		# 添加随机偏移（垂直于主方向）
		var perpendicular = Vector2(-segment_direction.y, segment_direction.x)
		var offset_magnitude = randf_range(-total_distance * 0.1, total_distance * 0.1)
		var offset = perpendicular * offset_magnitude
		
		# 计算下一个点
		current_point += segment_direction * segment_length + offset
		lightning_points.append(to_local(current_point))
	
	# 添加终点
	lightning_points.append(to_local(end_point))
